package com.genauth.sys.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.genauth.sys.dao.UserDao;
import com.genauth.sys.entity.AuthBean;
import com.genauth.sys.entity.MenuBean;
import com.genauth.sys.entity.RoleBean;
import com.genauth.sys.entity.UserBean;
import com.genauth.sys.util.CommonUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class UserService {
	@Resource
	private UserDao userdao;

	private Logger logger = LoggerFactory.getLogger(this.getClass());
	public void setUserdao(UserDao userdao) {
		this.userdao = userdao;
	}
	
	public List<UserBean> userLogin(UserBean user) throws Exception{
		logger.info("UserService.userLogin: user => "+user.toString());

		QueryWrapper<UserBean> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("USER_NAME",user.getUserName()).eq("USER_PASSWORD",user.getUserPassword());

		List<UserBean> users = userdao.userlogin(user);
		return users;
	}
	
	public List<UserBean> queryUserByName(String userName) {
		List<UserBean> users = new ArrayList<UserBean>();
//		if(StringUtils.isNotEmpty(userName)){
			users = userdao.queryUserInfoByName(userName);
//		}else{
//			users = userdao.getAllUserInfo();
//		}
		
		return users;
	}
	
	public List<RoleBean> queryRole() {
		List<RoleBean> roles = new ArrayList<>();
		roles = userdao.queryRole();
		return roles;
	}
	
	public List<AuthBean> queryAuthByUserName(String userName){
		return userdao.queryAuthByUserName(userName);
	}
	
	public List<Map<String,Object>> querySubMenu(){
		List<MenuBean> allMenu = userdao.querySubMenu();
		//把扁平结构的菜单数据转换成嵌套结构的菜单数据
		List<Map<String, Object>> allMenuMap = CommonUtils.beanList2Map(allMenu);

		String parentId = "0";
		List<Map<String, Object>> menuNodes = allMenuMap.stream().filter(menu -> parentId.equals(menu.get("parentId"))).collect(Collectors.toList());
		for(Map<String,Object> childNode:menuNodes){
			setChildNodes(childNode,allMenuMap);
		}
		return menuNodes;


//		List<Map<String,Object>> res = new ArrayList<>();
//		//Stream里面嵌套for循环。感觉怪怪的。
//		CommonUtils.beanList2Map(allMenu).stream()
//		.filter(menu -> "1".equals(menu.get("menuLevel")) && ("0").equals(menu.get("parentId")))
//		.forEach(menu->{
//			List<MenuBean> subMenus = new ArrayList<>();
//			for(MenuBean sMenu:allMenu){
//				if(StringUtils.isNotEmpty(sMenu.getParentId()) && sMenu.getParentId().equals(menu.get("menuId"))){
//					subMenus.add(sMenu);
//				}
//			}
//			menu.put("subMenus", CommonUtils.beanList2Map(subMenus));
//			res.add(menu);
//		});
//		return res;
	}

	private void setChildNodes(Map<String,Object> node,List<Map<String, Object>> allMenuMap){
		List<Map<String, Object>> childNodes = allMenuMap.stream().filter(menu -> node.get("menuId").equals(menu.get("parentId"))).collect(Collectors.toList());
		if(null != childNodes && childNodes.size()>0){
			node.put("subMenus",childNodes);
			for(Map<String,Object> childNode: childNodes){
				setChildNodes(childNode,allMenuMap);
			}
		}
	}

	public int updateMenu(UserBean user) {
		int opRes = 0;
//		String menuCodes = user.getUserMenucode();
//		for(String menuCode:menuCodes.split("\\|")){
//			if(StringUtils.isNotEmpty(menuCode)){
//				AuthBean ab = new AuthBean();
//				ab.setAuthCode(user.getUserName());
//				ab.setAuthType("U");
//				ab.setMenuCode(menuCode);
//				if(user.getUserPagecode().indexOf("|"+menuCode+"|")>=0){
//					ab.setPageCode(menuCode);
//				}
//				ab.setControllerCode(userdao.queryControllerByMenuCode(menuCode));
//				opRes += userdao.updateAuth(ab);
//			}
//		}
		return opRes;
	}

	public int deleteUser(String userId) {
		//删除用户角色对应关系
		userdao.deleteUserRole(userId);
		//删除用户信息 
		return userdao.delete(userId);
	}

	public int addUser(UserBean user) throws Exception {
		user.setUserPassword("123456");
		return userdao.addUser(user);
	}

	public int updateUser(UserBean user) throws Exception {
		return userdao.updateUser(user);
	}

	public int updateUserPassword(String userId, String oldPassword, String newPassword) {
		return userdao.updateUserPassword(userId,oldPassword,newPassword);
	}

	public int updateUserAndResetPass(UserBean user) {
		return userdao.updateUserAndResetPass(user);
	}

	public Map<String, Object> moveMenu() {
		Map<String,Object> res = new HashMap<String,Object>();
//		List<Map<String,Object>> allmenu = userdao.querySubMenu();
//		List<UserBean> allUser = userdao.getAllUser();
//		int opRes = 0;
//		for(UserBean user : allUser){
//			String menuCodes = user.getUserMenucode();
//			for(String menuCode:menuCodes.split("\\|")){
//				if(StringUtils.isNotEmpty(menuCode)){
//					AuthBean ab = new AuthBean();
//					ab.setAuthCode(user.getUserName());
//					ab.setAuthType("U");
//					ab.setMenuCode(menuCode);
//					if(user.getUserPagecode().indexOf("|"+menuCode+"|")>=0){
//						ab.setPageCode(menuCode);
//					}
//					ab.setControllerCode(userdao.queryControllerByMenuCode(menuCode));
//					opRes += userdao.insertAuth(ab);
//				}
//			}
//		}
//		res.put("userNum", allUser.size());
//		res.put("authNum", opRes);
		return res;
	}

	public int updateUR(String userId, String roles) {
		//先删除用户所有的角色对应关系
		userdao.deleteUserRole(userId);
		int res = 0 ; 
		//逐行添加用户角色对应关系
		String[] roleInfos = roles.split("\\|");
		for(int i = 0 ; i < roleInfos.length; i ++){
			String role = roleInfos[i];
			if(StringUtils.isNotEmpty(role)){
				res += userdao.updateUR(userId, role);
			}
		}
		return res;
	}

	public int addRole(RoleBean role) {
		return userdao.addRole(role);
	}

	public int delelteRole(String roleId) {
		//删除角色信息 
		return userdao.deleteRole(roleId);
	}

	public void deleteRA(String roleId) {
		userdao.deleteRA(roleId);
	}

	public int insertRA(String role,String raMenuId,String raMenuType,String raMenuControllerCode,String pageInfo) {
		return userdao.insertRA(role,raMenuId,raMenuType,raMenuControllerCode,pageInfo);
	}

	public int updateRole(RoleBean role) {
		return userdao.updateRole(role);
	}

	/**
	 * 生成用户有权限的左侧菜单树
	 * @param userId
	 * @return
	 */
	public List<Map<String,Object>> generateUserMenu(String userId) {
		List<Map<String,Object>> userMenuAuth = userdao.queryUserMenus(userId);

		List<Map<String,Object>> userMenuInfo = flat2Nest(userMenuAuth);

		return userMenuInfo;
	}

	//把平层的查询数据转换成前台要求的层级结构。
	private List<Map<String,Object>> flat2Nest(List<Map<String,Object>> flatList){
		List<Map<String,Object>> nestMap = new ArrayList<>();
		//tu.user_id,tu.role_id,tm.menu_id,tm.controller_code,tr.page_auth,tr.menu_type,tm.menu_code,tm.menu_name,tm.menu_icon,tm.parent_id,tm.menu_path
		flatList.stream().filter(menu -> menu.containsKey("menu_type") && "1".equals(menu.get("menu_type")))
				.forEach(parentMenu -> {
					Map<String,Object> menuInfo = new HashMap<>();
					menuInfo.put("path",parentMenu.get("menu_path"));
					menuInfo.put("name",parentMenu.get("menu_code"));
					menuInfo.put("meta",new HashMap<String,Object>(){{
						put("title",parentMenu.get("menu_name"));
						put("icon",parentMenu.get("menu_icon"));
					}});
					List<Map<String,Object>> childrenMenus = new ArrayList<>();

					flatList.stream()
							.filter(menu -> menu.containsKey("menu_type") && "2".equals(menu.get("menu_type")) && parentMenu.get("menu_id").equals(menu.get("parent_id")))
							.forEach(subMenu -> {
								Map<String,Object> subMenuInfo = new HashMap<>();
								subMenuInfo.put("path",subMenu.get("menu_path"));
								subMenuInfo.put("name",subMenu.get("menu_code"));
								subMenuInfo.put("meta",new HashMap<String,Object>(){{
									put("title",subMenu.get("menu_name"));
									put("icon",subMenu.get("menu_icon"));
								}});
								childrenMenus.add(subMenuInfo);
							});
					menuInfo.put("children",childrenMenus);
					nestMap.add(menuInfo);
		});

		return nestMap;
	}
}
